package com.neiquan.backstage.resourec_manage.webaction;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.common.util.Strings;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.Entrepreneur;
import com.neiquan.backstage.pub.bsc.dao.po.Lease;
import com.neiquan.backstage.pub.bsc.dao.po.Payment;
import com.neiquan.backstage.pub.bsc.dao.po.Station;
import com.neiquan.backstage.pub.bsc.dao.po.User;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;
import com.neiquan.backstage.resourec_manage.ResourecLeaseService;
import com.neiquan.backstage.resourec_manage.ResourecStationService;

@Controller
@RequestMapping(value = "resourecLease", produces = { "text/json;charset=UTF-8" })
public class ResourecLeaseAction {
	

	private static Class<?> poc = Lease.class;
	private static Class<?> pocS = Station.class;
	private static Class<?> pocE = Entrepreneur.class;
	private static Class<?> pocP = Payment.class;
	@Autowired
	private EntrepreneurService entrepreneurService;
	@Autowired
	private ResourecLeaseService resourecLeaseService;
	@Autowired
	private ResourecStationService resourecStationService;
	
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	
	/**
	 * 生成更换工位图
	 * @param 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"changeStationImg"})
	public String changeStationImg(int newlyStatus, int status,HttpSession session){
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		Map<String, Object> map = new HashMap<String,Object>();
		String uniqueId = user.getEntrepreneurUniqueId();
		Entrepreneur entityE = entrepreneurService.queryByEntrepreneurUnique(uniqueId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Station> listSC = resourecStationService.queryByEntrepreneurId(entrepreneurId,status,newlyStatus);
		List<Station> listSP = resourecStationService.queryByEntrepreneurId(entrepreneurId,Lease.status_pass , Lease.new_no);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", memberId));
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.build(Station.class, criterion);
		List<Station> listAllS = extraSpringHibernateTemplate.findAllByCriteria(queryCountCriteria);
		map.put("listSC", listSC);
		map.put("listS", listSP);
		map.put("listAllS", listAllS);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}
	@ResponseBody
	@RequestMapping(value={"changeRejectStationImg"})
	public String changeRejectStationImg(HttpSession session){
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		Map<String, Object> map = new HashMap<String,Object>();
		String uniqueId = user.getEntrepreneurUniqueId();
		Entrepreneur entityE = entrepreneurService.queryByEntrepreneurUnique(uniqueId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Station> listSC = new ArrayList<>();
		List<Lease> listL = resourecLeaseService.queryByEntrepreneurId(entrepreneurId, Lease.new_yes, Lease.status_change_reject);
		if(listL.size()>0){
			Lease netityL = listL.get(0);
			String changeStationIds = netityL.getChangeStationIds();
			String[] split = changeStationIds.split(",");
			for(String s:split){
				int stationId=Integer.parseInt(s);
				Station entityS = resourecStationService.queryByStationId(stationId);
				listSC.add(entityS);
			}
		}
		List<Station> listSP = resourecStationService.queryByEntrepreneurId(entrepreneurId,Lease.status_pass , Lease.new_no);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", memberId));
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.build(Station.class, criterion);
		List<Station> listAllS = extraSpringHibernateTemplate.findAllByCriteria(queryCountCriteria);
		map.put("listSC", listSC);
		map.put("listS", listSP);
		map.put("listAllS", listAllS);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}
	/**
	 * 添加更变工位
	 * @param 
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value={"addChange"})
	public String addChange(@RequestParam("stationIds[]")int[] stationIds,String endTime,HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		String entrepreneuruniqueId = user.getEntrepreneurUniqueId();
		Integer userId = user.getUserId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(entrepreneuruniqueId, memberId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		Lease entityL = new Lease();
		List<Lease> leases=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where entrepreneurId = ? and status!=2", entrepreneurId);
		if(leases.size()>0){
			entityL.setNewlyStuats(Lease.new_yes);
		}
		String uniqueId = UUID.randomUUID().toString();
		entityL.setUnquieId(uniqueId);
		entityL.setEntrepreneurId(entrepreneurId);
		entityL.setDtCreat(System.currentTimeMillis());
		entityL.setMemberId(memberId);
		entityL.setUserId(userId);
		entityL.setStatus(Lease.status_change_wait);
		entityL.setApplyType(Lease.apply_lease);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		long endTimeP = format.parse(endTime).getTime();
		entityL.setEndTime(endTimeP);
		String changeStationIds="";
		for(Integer stationId1:stationIds){
			changeStationIds+=stationId1+",";
		}
		changeStationIds = changeStationIds.substring(0,changeStationIds.length()-1);
		entityL.setChangeStationIds(changeStationIds);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entityL);
		Lease entityLL = resourecLeaseService.queryByUniqueId(memberId, uniqueId);
		Integer leaseId = entityLL.getLeaseId();
		List<Station> listS = resourecStationService.queryByEntrepreneurId(entrepreneurId, Lease.status_pass,Lease.new_no);
		for(int stationId:stationIds){
			boolean falge=false;
			for(Station s:listS){
				if(s.getStationId()==stationId){
					falge=true;
					break;
					}
				}
			if(!falge){
				Station entityS= resourecStationService.queryByStationId(stationId);	
				entityS.setLeaseId(leaseId);
				entityS.setState(Station.status_occupy);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
			}
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 重新申请
	 * @param 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"againApply"})
	public String againApply(int leaseId){
		Lease entityL = resourecLeaseService.queryById(leaseId);
		extraSpringHibernateTemplate.getHibernateTemplate().delete(entityL);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 生成新增工位图
	 * @param 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"stationImg"})
	public String stationImg(int newlyStatus, int status,int stationStatus,HttpSession session){
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		Map<String, Object> map = new HashMap<String,Object>();
		String uniqueId = user.getEntrepreneurUniqueId();
		Entrepreneur entityE = entrepreneurService.queryByEntrepreneurUnique(uniqueId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Lease> listL = resourecLeaseService.queryByEntrepreneurId(entrepreneurId,newlyStatus, status);
		if(listL.size()>0){
			List<Station> listS=new ArrayList<>();
			for(Lease entityL:listL){
				Integer leaseId = entityL.getLeaseId();
				List<Station> listSs = resourecStationService.queryAllByLeaseId(leaseId, stationStatus);
				for(Station s:listSs){
					listS.add(s);
				}
			}
			map.put("listS", listS);
		}else{
			map.put("listS", "nonentity");
		}
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", memberId));
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.build(Station.class, criterion);
		List<Station> listAllS = extraSpringHibernateTemplate.findAllByCriteria(queryCountCriteria);
		map.put("listAllS", listAllS);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}
	@ResponseBody
	@RequestMapping(value={"listApply"})
	public String listApply(int pageIndex, int pageSize,HttpSession session){
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Lease> listL = (List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("From Lease where memberId=? and status=?", memberId,Lease.status_wait);
		List<Object> list=new ArrayList<>();
		for(Lease l:listL){
			Map<String, Object> map = new HashMap<String, Object>();
			Entrepreneur entityE = entrepreneurService.queryById(l.getEntrepreneurId());
			map.put("endTime",l.getEndTime());
			map.put("name",entityE.getName());
			map.put("phone",entityE.getPhone());
			map.put("leaseId",l.getLeaseId());
			list.add(map);
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
	}
	/**
	 * 查询工位是否存在
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"queryisExistStation"})
	public String queryisExistStation(HttpSession session){
		User User = (User) Sessions.getLoginedUser(session);
		String  uniqueId= User.getEntrepreneurUniqueId();
		Integer memberId=User.getMemberId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(uniqueId, memberId);
		if(entityE==null){
			return CommonResp.buildSuccessResp().toJsonString();
		}
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Lease> listL= resourecLeaseService.queryByEntrepreneurId(entrepreneurId);
		return CommonResp.buildSuccessResp(listL).toJsonString();
	}
	
	/**
	 * 	条件查询
	 */
		@ResponseBody
		@RequestMapping(value={"search"})
		public String search(int pageIndex, int pageSize,String name,HttpSession session){
			AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
			Integer memberId = loginedUser.getMemberId();
			String likeName="%"+name+"%";
			List<Entrepreneur> listE = (List<Entrepreneur>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Entrepreneur where name like ? and memberId=?", likeName ,memberId);
			List<Object> list=new ArrayList<>();
			for(Entrepreneur e:listE){
				List<Lease> listL = resourecLeaseService.queryByEntrepreneurId(e.getEntrepreneurId(),Lease.new_no,Lease.status_pass);
				if(listL.size()>0){
					Lease entityL = listL.get(0);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("endTime",entityL.getEndTime());
					map.put("name",e.getName());
					map.put("phone",e.getPhone());
					map.put("leaseId",entityL.getLeaseId());
					list.add(map);
				}
			}
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
		
	/**
	 * 申请更变工位
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value={"changeStation"})
	public String changeStation(@RequestParam("stationIds[]")Integer[] stationIds,Integer leaseId,String endeTime) throws ParseException {
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		List<Station> listS = resourecStationService.queryAllByLeaseId(leaseId, Station.status_lease);
		for(Station s:listS){
			s.setLeaseId(null);
			s.setState(Station.status_free);
			extraSpringHibernateTemplate.getHibernateTemplate().update(s);
		}
		for(Integer id:stationIds){
			Station s = resourecStationService.queryById(id);
			s.setLeaseId(leaseId);
			s.setState(Station.status_lease);
			extraSpringHibernateTemplate.getHibernateTemplate().update(s);
		}
		SimpleDateFormat simpl = new SimpleDateFormat("yyyy-MM-dd");
		long time = simpl.parse(endeTime).getTime();
		entityL.setEndTime(time);
		extraSpringHibernateTemplate.getHibernateTemplate().update(entityL);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 通过entrepreneurId查询Station类
	 */
	@ResponseBody
	@RequestMapping(value={"queryByEntrepreneurId"})
	public String queryByEntrepreneurId(String entrepreneurId) {
		if(Strings.trimAndNotNull(entrepreneurId)==null||"".equals(entrepreneurId)){
			return CommonResp.buildSuccessResp().toJsonString();
		}
		int id = Integer.parseInt(entrepreneurId);
		Entrepreneur entityE = entrepreneurService.queryById(id);
		Lease entityL = resourecLeaseService.queryByEntrepreneurId(id, Lease.new_no);
		List<Station> listS = resourecStationService.queryAllByLeaseId(entityL.getLeaseId(),Station.status_lease);
		Map<String ,Object> map = new HashMap<String ,Object>();
		map.put("entrepreneur", entityE);
		map.put("stations", listS);
		map.put("lease", entityL);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}
	/**
	 * 通过leaseId查询该公司下所有订单和该公司的所有租用的工位
	 */
	@ResponseBody
	@RequestMapping(value={"queryByIdStationEntrepreneur"})
	public String queryByIdStationEntrepreneur(Integer leaseId) {
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		Integer entrepreneurId = entityL.getEntrepreneurId();
		Entrepreneur entityE = entrepreneurService.queryById(entrepreneurId);
		List<Station> listS = resourecStationService.queryAllByLeaseId(entityL.getLeaseId(),Station.status_lease);
		Map<String, Object> mapL = new HashMap<>();
		mapL.put("stations", listS);
		mapL.put("lease", entityL);
		mapL.put("entrepreneur", entityE);
		return CommonResp.buildSuccessResp(mapL).toJsonString();
	}
	
	@ResponseBody
	@RequestMapping(value={"list"})
	public String list(int pageIndex, int pageSize,HttpSession session){
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Lease> listL = resourecLeaseService.queryByMeberId(memberId,Lease.new_no,Lease.status_pass);
		List<Object> list=new ArrayList<>();
		for(Lease l:listL){
			Map<String, Object> map = new HashMap<String, Object>();
			Entrepreneur entityE = entrepreneurService.queryById(l.getEntrepreneurId());
			map.put("endTime",l.getEndTime());
			map.put("name",entityE.getName());
			map.put("phone",entityE.getPhone());
			map.put("leaseId",l.getLeaseId());
			list.add(map);
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
	}
	/**
	 * 通过名字查询一个Entrepreneur
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryByNameEntrepreneur")
	public String queryByNameEntrepreneur(String name,HttpSession session) throws ParseException {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		
		Entrepreneur entityE = entrepreneurService.queryByName(name, memberId);
		return CommonResp.buildSuccessResp(entityE).toJsonString();
	}
	/**
	 * 恢复更换失败状态为正常状态
	 */
	@ResponseBody
	@RequestMapping(value={"recoverChange"})
	public String recoverChange(Integer leaseId) {
		Lease entityL=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
				entityL.setStatus(1);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entityL);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 审核更换表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"auditChange"})
	public String auditChange(Integer leaseId,Integer status,String changeRemark) {
		Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		if(entity==null){
			CommonResp.buildSuccessResp(BackendErrorCode.not_exist).toJsonString();
		}else{
			if(status==4){
				entity.setStatus(status);
				entity.setChangeRemark(changeRemark);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
				String strChangeStationIds = entity.getChangeStationIds();
				String[] strings = strChangeStationIds.split(",");
				for(String st:strings){
					if(st!=null&&!"".equals(st)){
						int stationId = Integer.parseInt(st);
						Station entityS=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
						if(entityS.getState()==3){
							entityS.setState(0);
						}
					}
				}
				return CommonResp.buildSuccessResp("审核未通过").toJsonString();
			}else{ 
				entity.setStatus(status);
				entity.setStationRemark(changeRemark);
				String strChangeStationIds = entity.getChangeStationIds();
				entity.setMomentStationIds(strChangeStationIds);
				String strMomentStationIds = entity.getMomentStationIds();
				extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
				String[] strings = strMomentStationIds.split(",");
				for(String st:strings){
					if(st!=null&&!"".equals(st)){
						int stationId = Integer.parseInt(st);
						Station entityS=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
						entityS.setLeaseId(-1);
						entityS.setState(0);
						extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
					}
				}
				String[] strings1 = strChangeStationIds.split(",");
				for(String st1:strings1){
					if(st1!=null&&!"".equals(st1)){
						int stationId = Integer.parseInt(st1);
						Station entityS=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
						entityS.setLeaseId(leaseId);
						entityS.setState(1);
						extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
					}
				}
				return CommonResp.buildSuccessResp("审核通过").toJsonString();
			}	
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 查看更变工位
	 */
	@ResponseBody
	@RequestMapping(value={"seeChangeStation"})
	public String seeChangeStation(Integer leaseId) {
		Lease entityL=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		List<Station> stations = (List<Station>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("FROM Station s WHERE leaseId=? GROUP BY s.zone", leaseId);
		List list=new ArrayList();
		/*for(Station sta:stations){
			list.add(sta.getZone());
		}*/
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("zones", list);
		map.put("changeStationIds", entityL.getChangeStationIds());
		map.put("momentStationIds", entityL.getMomentStationIds());
		Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "leaseId", leaseId);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}

	/**
	 * 申请更变工位
	 */
	@ResponseBody
	@RequestMapping(value={"changeStationWait"})
	public String changeStationWait(@RequestParam("stationIds[]")Integer[] stationIds,Integer leaseId) {
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		entityL.setStatus(3);
		String changeStationIds="";
		for(Integer stationId1:stationIds){
				changeStationIds+=stationId1+",";
		}
		entityL.setChangeStationIds(changeStationIds);
		extraSpringHibernateTemplate.getHibernateTemplate().update(entityL);
		for(Integer stationId:stationIds){
			Station entityS=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
			if(entityS.getState()==0){
				entityS.setState(3);
			}
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 通过leaseId查询Station类
	 */
	@ResponseBody
	@RequestMapping(value={"querySeeStation"})
	public String querySeeStation(Integer leaseId) {
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		String stationIds = entityL.getMomentStationIds();
		String[] strs = stationIds.split(",");
		List<Station> list=new ArrayList<Station>();
		for(int i=0;i<strs.length;i++){
			if(!"".equals(strs[i])&&strs[i]!=null){
				Station entityS=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", Integer.parseInt(strs[i]));
				list.add(entityS);
			}
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
	}
	/**
	 * 通过公司名查询该公司下lesaeId
	 */
	@ResponseBody
	@RequestMapping(value={"queryByEntNamelesaeId"})
	public String queryByEntNamelesaeId(String name) {
		Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "name", name);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Station> find = (List<Station>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("FROM Station s WHERE entrepreneur=? AND status==1",entrepreneurId );
		Station station = find.get(0);
		return CommonResp.buildSuccessResp(station).toJsonString();
	}
	/**
	 * 审核出租表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"auditLease"})
	public String auditLease(@RequestParam("stationIds[]")Integer[] stationIds,Integer leaseId,Integer status,String stationRemark) {
		Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		if(entity==null){
			CommonResp.buildSuccessResp(BackendErrorCode.not_exist).toJsonString();
		}else{
			if(status==2){
				entity.setStatus(status);
				entity.setStationRemark(stationRemark);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
				for(Integer stationId:stationIds){
					Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
					entityS.setLeaseId(null);
					entityS.setState(Station.status_free);
					extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
				}
				return CommonResp.buildSuccessResp("审核未通过").toJsonString();
			}else{ 
				entity.setStatus(status);
				entity.setStationRemark(stationRemark);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
				for(Integer stationId:stationIds){
					Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
					entityS.setLeaseId(leaseId);
					entityS.setState(Station.status_lease);
					extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
				}
				return CommonResp.buildSuccessResp("审核通过").toJsonString();
			}	
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 查询指定是lease对象
	 * @return
	 */
		@ResponseBody
		@RequestMapping(value={"queryLease"})
		public String queryLease(Integer leaseId) {
			Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
			return CommonResp.buildSuccessResp(entity).toJsonString();
		}
	/**
	 * 查询指定是Entrepreneur对象
	 */
		@ResponseBody
		@RequestMapping(value={"queryEntrepreneur"})
		public String queryEntrepreneur(Integer leaseId) {
			// TODO Auto-generated method stub
			Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
			Integer entrepreneurId = entity.getEntrepreneurId();
			Entrepreneur entrepreneur= extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
			return CommonResp.buildSuccessResp(entrepreneur).toJsonString();
		}
	/**
	* 查询去重是zone对象
	*/
	@ResponseBody
	@RequestMapping(value={"queryZones"})
	public String queryZones(Integer leaseId,HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Station> find = extraSpringHibernateTemplate.findAllByPropEq(pocS, "leaseId", leaseId);
		List<Station> list=new ArrayList<Station>();
		Lease lease=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		String momentStationIds = lease.getMomentStationIds();
		String[] str=momentStationIds.split(",");
		for(int i=0;i<str.length;i++){
			Integer stationId = Integer.parseInt(str[i]);
			Station station=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
				list.add(station);
				break;
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
	}	
	/**
	* 查询去重是zone对象
	*/
	@ResponseBody
	@RequestMapping(value={"queryStations"})
	public String queryStations(Integer leaseId) {
		// TODO Auto-generated method stub
		List<Station> find = extraSpringHibernateTemplate.findAllByPropEq(pocS, "leaseId", leaseId);
		List<Station> list=new ArrayList<Station>();
		Lease lease=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		String momentStationIds = lease.getMomentStationIds();
		String[] str=momentStationIds.split(",");
		for(int i=0;i<str.length;i++){
			Integer stationId = Integer.parseInt(str[i]);
			Station station=extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
				list.add(station);
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
	}	
	/**
	 * 	分页查询所有
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"listArrearage"})
	public String listArrearage(int pageIndex, int pageSize,HttpSession session){
		List list=new ArrayList();
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		 List<Lease> entitysL=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where memberId=?", memberId);
		if(entitysL==null||entitysL.size()<=0){
			return CommonResp.buildSuccessResp().toJsonString();
		}else{
		for(Lease lease:entitysL){
			Map<String,Object> map=new HashMap<String,Object>();
			Integer entrepreneurId = lease.getEntrepreneurId();
			Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
			if(entityE!=null){
				double arrearage=0;
				String linkman=entityE.getLinkman();
				String phone=entityE.getPhone();
				String eName=entityE.getName();
				Long lStratTime=lease.getStratTime();
				Long lEndTime=lease.getEndTime();
			/**
			 * 计算欠费
			 */
			Integer paymentId = lease.getPaymentId();
			Payment entityP = extraSpringHibernateTemplate.findFirstOneByPropEq(pocP, "paymentId", paymentId);
			if(entityP!=null){
				entityP.getEndTime();
				double sumRental=lease.getSumRental();
				long currentTimeMillis = System.currentTimeMillis();
				DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
				String stri = dateFormat.format(currentTimeMillis);
				map.put("pEndTime", entityP.getEndTime());
				String payEndTime = dateFormat.format(entityP.getEndTime());
				String 	str1=stri.substring(0,4);
				String	str2=stri.substring(4,2);
				String	str3=stri.substring(6,2);
				Integer currentYear=Integer.parseInt(str1);
				Integer currentMonth=Integer.parseInt(str2);
				Integer currentDay=Integer.parseInt(str3);
				String 	stri1=payEndTime.substring(0,4);
				String	stri2=payEndTime.substring(4,2);
				String	stri3=payEndTime.substring(6,2);
				Integer payYear=Integer.parseInt(stri1);
				Integer payMonth=Integer.parseInt(stri2);
				Integer payDay=Integer.parseInt(stri3);
				if(currentYear==payYear){
					if(currentMonth==payMonth){
						if(currentDay>payDay){
							arrearage=sumRental;
						}
						if(currentMonth>currentMonth){
							int a=currentMonth-payMonth;
							if(currentDay>payDay){
								arrearage=(a+1)*sumRental;
							}else{
								arrearage=a*sumRental;
							}
						}
					}
				}else {
					Integer b=currentYear-payYear;
					arrearage=b*12+currentMonth-payMonth;
				}
				map.put("arrearage", arrearage);
			}
			/**
			 * 封装数据
			 */
			map.put("linkman", linkman);
			map.put("phone", phone);
			map.put("eName", eName);
			map.put("lStratTime", lStratTime);
			map.put("lEndTime", lEndTime);
			map.put("status", lease.getStatus());
			map.put("leaseId", lease.getLeaseId());
			list.add(map);
			}
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
		}
	} 
	
	/**
	 * 添加新增出租对象
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value={"addNewlyLease"})
	public String addNewlyLease(@RequestParam("stationIds[]")Integer[] stationIds,String endTime,String startTime,
			double sumRental,HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		String uniqueId = user.getEntrepreneurUniqueId();
		Integer userId = user.getUserId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(uniqueId, memberId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		Lease entity = new Lease();
		List<Lease> leases=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where entrepreneurId = ? and status!=2", entrepreneurId);
		if(leases.size()>0){
			entity.setNewlyStuats(Lease.new_yes);
		}
		entity.setStatus(Lease.status_wait);
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		entity.setStratTime(dateFormat.parse(Strings.trimAndNotNull(startTime)).getTime());
		entity.setEndTime(dateFormat.parse(Strings.trimAndNotNull(endTime)).getTime());
		entity.setEntrepreneurId(entrepreneurId);
		entity.setSumRental(sumRental);
		String momentStationIds="";
		for(Integer stationId1:stationIds){
			momentStationIds+=stationId1+",";
		}
		momentStationIds = momentStationIds.substring(0,momentStationIds.length()-1);
		entity.setMemberId(memberId);
		entity.setUserId(userId);
		entity.setDtCreat(System.currentTimeMillis());
		entity.setApplyType(Lease.apply_lease);
		entity.setMomentStationIds(momentStationIds);
		String randomUUID = UUID.randomUUID().toString();
		entity.setUnquieId(randomUUID);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entity);
		Lease entity1 = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "unquieId", randomUUID);
		Integer leaseId = entity1.getLeaseId();
		for(Integer stationId:stationIds){
			Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
			entityS.setLeaseId(leaseId);
			entityS.setState(Station.status_occupy);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 添加出租对象
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value={"addLease"})
	public String addLease(@RequestParam("stationIds[]")Integer[] stationIds,Integer monthNumber,
			double totalPrice,String endTime,String startTime,double sumRental,
			HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		String uniqueId = user.getEntrepreneurUniqueId();
		Integer userId = user.getUserId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(uniqueId, memberId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		user.getEntrepreneurUniqueId();
		Lease entity = new Lease();
		List<Lease> leases=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where entrepreneurId = ? and status!=2", entrepreneurId);
		if(leases.size()>0){
			entity.setNewlyStuats(Lease.new_yes);
		}else{
			entity.setNewlyStuats(Lease.new_no);
		}
		entity.setUserId(userId);
		entity.setStatus(Lease.status_wait);
		entity.setMonthNumber(monthNumber);
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		entity.setStratTime(dateFormat.parse(Strings.trimAndNotNull(startTime)).getTime());
		entity.setEndTime(dateFormat.parse(Strings.trimAndNotNull(endTime)).getTime());
		entity.setEntrepreneurId(entrepreneurId);
		entity.setTotalPrice(totalPrice);
		entity.setSumRental(sumRental);
		String momentStationIds="";
		for(Integer stationId1:stationIds){
			momentStationIds+=stationId1+",";
		}
		momentStationIds = momentStationIds.substring(0,momentStationIds.length()-1);
		entity.setMomentStationIds(momentStationIds);
		momentStationIds = momentStationIds.substring(0,momentStationIds.length()-1);
		entity.setMemberId(memberId);
		entity.setApplyType(Lease.apply_lease);
		String randomUUID = UUID.randomUUID().toString();
		entity.setUnquieId(randomUUID);
		entity.setDtCreat(System.currentTimeMillis());
		extraSpringHibernateTemplate.getHibernateTemplate().save(entity);
		Lease entity1 = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "unquieId", randomUUID);
		Integer leaseId = entity1.getLeaseId();
		for(Integer stationId:stationIds){
			Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
			entityS.setLeaseId(leaseId);
			entityS.setState(Station.status_occupy);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 查询所有queryAll zone group by去重
	 * @return
	 */
		@ResponseBody
		@RequestMapping(value={"queryAll"})
		public String queryAll(HttpSession session) {
			AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
			Integer memberId = loginedUser.getMemberId();
			DetachedCriteria dc = DetachedCriteria.forClass(Station.class);
			dc.add(Restrictions.eq("memberId",memberId));
			dc.setProjection(Projections.alias(Projections.groupProperty("zone"),"zone"));
			 List<Station> list = extraSpringHibernateTemplate.findAllByCriteria(dc);
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
		
}
